﻿using Grow.Domain.EventBus.Cap.SubscriberDomainEvents;
using Grow.Module.Service;
using Grow.Scheduler.Job;

namespace Grow.Domain.EventBus.Cap.Jobs
{
    public class RetrySubscriberDomainEventJob : JobBase
    {
        private readonly ISubscriberDomainEventService _subscriberDomainEventService;
       
        private readonly ISubscriberDomainEventHandler _subscriberDomainEventHandler;
        public RetrySubscriberDomainEventJob(IServiceContext serviceContext) : base(serviceContext)
        {
            _subscriberDomainEventService = serviceContext.GetRequiredService<ISubscriberDomainEventService>();

            _subscriberDomainEventHandler = _serviceContext.GetRequiredService<ISubscriberDomainEventHandler>();

        }


        public override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            List<SubscriberDomainEventDto> subscriberDomainEventDtos = await _subscriberDomainEventService.GetSubscriberDomainEventsOfNeedRetryAsync(cancellationToken);
            if (subscriberDomainEventDtos.Count == 0)
            {
                return;
            }
            _ = Parallel.ForEach(subscriberDomainEventDtos, subscriberDomainEventDto =>
            {
                _ = Task.Factory.StartNew(async () =>
                {
                    await _subscriberDomainEventHandler.SubscriberAsync(subscriberDomainEventDto, cancellationToken);
                }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            });
        }

     
    }
}
